package com.android.car.screensaver;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnSystemUiVisibilityChangeListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class ScreenSaver extends Activity {

    private static final String TAG = "ScreenSaver";
    private WakeLock mLock;
    private PowerManager mManager;
    private WindowManager mWManager;
    private RelativeLayout mRootView;
    private GestureDetector mGestureDetector;
    private TextView mDateView = null;
    private DigitalClock mTimeView = null;
    private SimpleDateFormat dateFormatter = null;
    private final int BASE_SYS_UI_VISIBILITY =
            View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
            | View.SYSTEM_UI_FLAG_FULLSCREEN;
    private static final String FONT_DIGITAL_7 = "fonts" + File.separator
            + "digital-7.ttf";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        mManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        mWManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        getWindow().getDecorView().setSystemUiVisibility(
                BASE_SYS_UI_VISIBILITY | View.SYSTEM_UI_FLAG_LOW_PROFILE);

        getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(
                new OnSystemUiVisibilityChangeListener() {
                    @Override
                    public void onSystemUiVisibilityChange(int visibility) {
                        Log.d(TAG, "[onSystemUiVisibilityChange] visibility: " + visibility);
                        if (View.VISIBLE == visibility) {
                            getWindow().getDecorView().setSystemUiVisibility(
                                    BASE_SYS_UI_VISIBILITY | View.SYSTEM_UI_FLAG_LOW_PROFILE);
                        }
                    }
                });
        dateFormatter
            = new SimpleDateFormat(getResources().getString(R.string.date_format));
        setContentView(R.layout.screen_saver);
        mRootView = (RelativeLayout) findViewById(R.id.saver);
        mDateView = (TextView) findViewById(R.id.date);
        mTimeView = (DigitalClock) findViewById(R.id.time);
        AssetManager assets = getAssets();
        final Typeface font = Typeface.createFromAsset(assets, FONT_DIGITAL_7);
        mDateView.setTypeface(font, R.style.SaverTextStyle);
        mTimeView.setTypeface(font, R.style.SaverTextStyle);
        updateDateView();
        mGestureDetector = new GestureDetector(this, mGestureListener);
        mGestureDetector.setOnDoubleTapListener(mDoubleTabListener);
    }

    @Override
    protected void onStart() {
        Log.d(TAG, "[onStart]");
        super.onStart();
        sendBroadcast(new Intent("rk.android.hide.navi")); // no where to handle this broadcast
    }

    private GestureDetector.OnGestureListener mGestureListener = new GestureDetector.OnGestureListener() {

        @Override
        public boolean onDown(MotionEvent e) {
            return false;
        }

        @Override
        public void onShowPress(MotionEvent e) {
        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            return false;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            return false;
        }

        @Override
        public void onLongPress(MotionEvent e) {
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            return false;
        }

    };

    private GestureDetector.OnDoubleTapListener mDoubleTabListener = new GestureDetector.OnDoubleTapListener() {

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            return false;
        }

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            return false;
        }

        @Override
        public boolean onDoubleTapEvent(MotionEvent e) {
            ScreenSaver.this.finish();
            return true;
        }
    };

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Log.d(TAG, "[onTouchEvent] event: " + event.getAction());
        return mGestureDetector.onTouchEvent(event);
    }

    private BroadcastReceiver mDateChangeListener = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "[onReceive] action: " + intent.getAction());
            if (Intent.ACTION_DATE_CHANGED.equals(intent.getAction())) {
                updateDateView();
            }
        }
    };

    private void updateDateView() {
        // get the current date
        Date curDate = new Date(System.currentTimeMillis());
        Calendar cal = Calendar.getInstance();
        cal.setTime(curDate);
        int weekday = cal.get(Calendar.DAY_OF_WEEK);
        String date = dateFormatter.format(curDate) + " " + getWeekDay(weekday);
        Log.d(TAG, "[updateDateView] date: " + date);
        if (mDateView != null) {
            mDateView.setText(date);
        }
    }

    private String getWeekDay(int day) {
        Resources resource = getResources();
        String today = null;
        if (day == 2) {
            today = resource.getString(R.string.week_monday);
        } else if (day == 3) {
            today = resource.getString(R.string.week_tuesday);
        } else if (day == 4) {
            today = resource.getString(R.string.week_wednesday);
        } else if (day == 5) {
            today = resource.getString(R.string.week_thursday);
        } else if (day == 6) {
            today = resource.getString(R.string.week_friday);
        } else if (day == 7) {
            today = resource.getString(R.string.week_saturday);
        } else if (day == 1) {
            today = resource.getString(R.string.week_sunday);
        }
        return today;
    }

    @Override
    protected void onResume() {
        Log.d(TAG, "[onResume]");
        if (mManager != null) {
            mLock = mManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK
                    | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "ScreenSaver");
            mLock.acquire();
        }
        registerReceiver(mDateChangeListener, new IntentFilter(Intent.ACTION_DATE_CHANGED));
        super.onResume();
    }

    @Override
    protected void onPause() {
        Log.d(TAG, "[onPause]");
        unregisterReceiver(mDateChangeListener);
        if (mLock != null) {
            mLock.release();
        }
        super.onPause();
    }

    @Override
    protected void onStop() {
        Log.d(TAG, "[onStop]");
        sendBroadcast(new Intent("rk.android.show.navi"));
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        Log.d(TAG, "[onDestroy]");
        super.onDestroy();
    }
}
